import request from '@/utils/http';
import { jsonToUrlParam, getApiUrl } from '@/utils/urlSearchParams';
import type {
  GetOrganizationsInput,
  OrganizationDto,
  OrganizationTreeDto,
  CreateOrganizationDto,
  UpdateOrganizationDto
} from './type';
import type { PagedResultDto } from '../type';

enum API {
  DEFAULT_URL = '/api/basics/organizations',
  SELECT_URL = '/api/basics/organizations/select',
  TREE_URL = '/api/basics/organizations/tree'
}

// 列表接口
export const getListAsync = (input: GetOrganizationsInput) => {
  const paramenter = jsonToUrlParam(input);
  const url = getApiUrl(API.DEFAULT_URL, paramenter);
  return request.get<PagedResultDto<OrganizationTreeDto>>(url);
};

// 详情接口
export const getAsync = (id: string) => request.get<OrganizationDto>(`${API.DEFAULT_URL}/${id}`);

// 创建
export const createAsync = (input: CreateOrganizationDto) =>
  request.post<OrganizationDto>(API.DEFAULT_URL, input);

// 更新
export const updateAsync = (id: string, input: UpdateOrganizationDto) =>
  request.put<OrganizationDto>(`${API.DEFAULT_URL}/${id}`, input);

//组织树
export const getTreeAsync = (parentId?: string) => {
  let url: string = API.TREE_URL;
  if (parentId) {
    url += `?parentId=${parentId}`;
  }
  return request.get<OrganizationDto[]>(url);
};

// 组织集合
export const getSelectAsync = (recursive: boolean = false, parentId?: string) => {
  let url: string = `${API.SELECT_URL}?recursive=${recursive}`;
  if (parentId) {
    url += `&parentId=${parentId}`;
  }
  return request.get<OrganizationDto[]>(url);
};

// 删除
export const deleteAsync = (id: string) => request.delete<void>(`${API.DEFAULT_URL}/${id}`);
